package com.example.graduation.controller;


import com.example.graduation.entity.Shop;
import com.example.graduation.entity.User;
import com.example.graduation.form.*;
import com.example.graduation.service.UserService;
import com.example.graduation.service.impl.UserServiceImpl;
import com.example.graduation.util.JwtUtil;
import com.example.graduation.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xyc
 * @since 2022-02-11
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserServiceImpl userServiceimpl;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private JwtUtil jwtUtil;

    //redis设置的缓存过期时间
    @Value("${jwt.redisExpire}")
    private Integer redisExpire;


    /**
     * @api {POST} /user/register 用户注册
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName register
     * @apiParam (请求体) {String} tel 手机号码
     * @apiParam (请求体) {String} email 邮箱号码
     * @apiParam (请求体) {String} code  微信临时授权码
     * @apiParam (请求体) {String} password 用户密码
     * @apiParam (请求体) {String} nickname 用户名称（微信提供）
     * @apiParam (请求体) {String} photo 用户头像
     * @apiParamExample 请求体示例
     * {"password":"EOs4l","code":"jZS","nickname":"A","photo":"28KOGsOBE4","tel":"Nz","email":"ygis2oz"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody RegisterForm form) {
        Integer userId = userService.register(form.getTel(), form.getEmail(), form.getPassword(), form.getCode(), form.getNickname(), form.getPhoto());
        String token = jwtUtil.createToken(userId);
        Set<String> permission = userService.searchPermissionById(userId);
        saveCacheToken(token, userId);
        return R.ok().put("token", token).put("permission", permission);
    }


    /**
     * @api {POST} /user/login 微信登录
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName login
     * @apiParam (请求体) {String} code 微信临时授权码
     * @apiParamExample 请求体示例
     * {"code":"TdLTQeJ8"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody LoginCode code) {
        Integer userId = userService.login(code.getCode());
        String token = jwtUtil.createToken(userId);
        log.info("用户token:{}", token);
        Set<String> permission = userService.searchPermissionById(userId);
        saveCacheToken(token, userId);
        return R.ok().put("token", token).put("permission", permission);
    }


    /**
     * @api {POST} /user/anotherLogin 邮箱或者手机号码+用户密码登录
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName anotherLogin
     * @apiParam (请求体) {String} account 账号（邮箱或者手机号码）
     * @apiParam (请求体) {String} password 密码
     * @apiParamExample 请求体示例
     * {"password":"ZUMIv5","account":"WHBWf"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/anotherLogin")
    @ResponseBody
    public R anotherLogin(@RequestBody AnotherLoginForm form) {
        Integer userId = userService.login(form.getAccount(), form.getPassword());
        String token = jwtUtil.createToken(userId);
        Set<String> permission = userService.searchPermissionById(userId);
        saveCacheToken(token, userId);
        System.out.println(token);
        return R.ok().put("token", token).put("permission", permission);
    }


    /**
     * @api {POST} /user/emailLogin 发送邮箱验证码
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName sendCode
     * @apiParam (请求体) {String} email 邮箱号码
     * @apiParamExample 请求体示例
     * {"email":"IsH"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/sendCode")
    @ResponseBody
    public R sendCode(@RequestBody EmailForm form) {
        String code = userService.sendCode(form.getEmail());
        log.info("邮箱验证码为：{}", code);
        return R.ok("邮箱发送成功，请注意查收");
    }


    /**
     * @api {POST} /user/emailLogin 邮箱+验证码登录
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName emailLogin
     * @apiParam (请求体) {String} email 邮箱号码
     * @apiParam (请求体) {String} code 邮箱验证码
     * @apiParamExample 请求体示例
     * {"code":"eyQRACjvBX","email":"LD"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @ResponseBody
    @PostMapping("/emailLogin")
    public R emailLogin(@RequestBody EmailLoginForm form) {
        Integer userId = userService.loginByEmailCode(form.getEmail(), form.getCode());
        String token = jwtUtil.createToken(userId);
        Set<String> permission = userService.searchPermissionById(userId);
        saveCacheToken(token, userId);
        return R.ok().put("token", token).put("permission", permission);
    }


    /**
     * 把token存进redis中，token为键，user+""为值
     *
     * @param token
     * @param userId
     * @author xieyucan
     * CreateDate 2022/2/19 12:52
     */
    private void saveCacheToken(String token, Integer userId) {
        redisTemplate.opsForValue().set(token, userId + "", redisExpire, TimeUnit.DAYS);
    }


    /**
     * @api {POST} /user/apply 用户申请为商家
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName apply
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=9jE8
     * @apiParam (请求体) {Number} shopId
     * @apiParam (请求体) {Number} userId
     * @apiParam (请求体) {Number} goodsId
     * @apiParam (请求体) {Number} status
     * @apiParam (请求体) {String} position
     * @apiParam (请求体) {Number} createTime
     * @apiParam (请求体) {String} name
     * @apiParam (请求体) {String} license
     * @apiParam (请求体) {String} openTime
     * @apiParam (请求体) {String} active
     * @apiParam (请求体) {Number} freight
     * @apiParam (请求体) {String} photo
     * @apiParam (请求体) {String} content
     * @apiParamExample 请求体示例
     * {"goodsId":5906,"freight":9039,"active":"8","photo":"cdAyQ54A","userId":8677,"content":"Ak","license":"G1jTgobnDR","createTime":6603,"name":"E","shopId":7693,"position":"zGV","openTime":"3","status":7788}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/apply")
    @ResponseBody
    public R apply(@RequestHeader String token, @RequestBody Shop shop) {
        Boolean apply = userService.apply(token, shop.getPosition(), shop.getName(),
                shop.getPhoto(), shop.getContent(), shop.getLicense(), shop.getShoptype());
        if (apply == true) {
            return R.ok("申请发送成功").put("shop", shop);
        } else {
            return R.error("消息发送失败");
        }
    }


    /**
     * @api {POST} /user/findUserInfo 查询用户基本信息
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName findUserInfo
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=vDWhu2K
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/findUserInfo")
    @ResponseBody
    public R findUserInfo(@RequestHeader String token) {
        User user = userServiceimpl.findUserInfo(token);
        return R.ok().put("user", user);
    }


    /**
     * @api {POST} /user/changeUserInfo 修改用户头像
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName changeUserInfo
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=0uL2pB3
     * @apiParam (请求体) {String} photo
     * @apiParamExample 请求体示例
     * {"photo":"k1Y6"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/changeUserInfo")
    @ResponseBody
    public R changeUserInfo(@RequestHeader String token, @RequestBody PhotoForm form) {
        userServiceimpl.changeUserInfo(token, form.getPhoto());
        return R.ok("修改成功");
    }


    /**
     * @api {POST} /user/changeUserName 改变用户的信息
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName changeUserName
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=1CB5ps1wq
     * @apiParam (请求体) {String} name
     * @apiParam (请求体) {String} phone
     * @apiParam (请求体) {String} sex
     * @apiParamExample 请求体示例
     * {"phone":"ywkw155Z","sex":"P","name":"xsRaZTVdl"}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/changeUserName")
    @ResponseBody
    public R changeUserName(@RequestHeader String token, @RequestBody UserInfo info) {
        userServiceimpl.changeUserName(token, info.getName(), info.getPhone(), info.getSex());
        return R.ok();
    }


    /**
     * @api {POST} /user/position1 插入用户的经纬度
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName position1
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=d5eI29P68
     * @apiParam (请求体) {Number} lat
     * @apiParam (请求体) {Number} lon
     * @apiParamExample 请求体示例
     * {"lon":7958.15,"lat":2483.75}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/position1")
    @ResponseBody
    public R position1(@RequestHeader String token, @RequestBody PositionForm form) {
        userServiceimpl.position1(token, form.getLat(), form.getLon());
        return R.ok();
    }


    /**
     * @api {POST} /user/findUserList 查询用户列表
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName findUserList
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/findUserList")
    @ResponseBody
    public R findUserList() {
        List<User> list = userServiceimpl.findUserList();
        return R.ok().put("list", list);
    }


    /**
     * @api {POST} /user/findUser 查询用户
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName findUser
     * @apiParam (请求体) {Number} shopId
     * @apiParamExample 请求体示例
     * {"shopId":9132}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/findUser")
    @ResponseBody
    public R findUser(@RequestBody IdForm form) {
        User user = userServiceimpl.findUser(form.getShopId());
        return R.ok().put("user", user);
    }


    /**
     * @api {POST} /user/deleteUser 假删除用户
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName deleteUser
     * @apiParam (请求体) {Number} shopId
     * @apiParamExample 请求体示例
     * {"shopId":8481}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/deleteUser")
    @ResponseBody
    public R deleteUser(@RequestBody IdForm form) {
        userServiceimpl.deleteUser(form.getShopId());
        return R.ok();
    }


    /**
     * @api {POST} /user/warmUser 发送警告消息给用户
     * @apiVersion 1.0.0
     * @apiGroup UserController
     * @apiName warmUser
     * @apiParam (请求参数) {String} token
     * @apiParamExample 请求参数示例
     * token=NdSUQm
     * @apiParam (请求体) {Number} shopId
     * @apiParamExample 请求体示例
     * {"shopId":6901}
     * @apiSuccess (响应结果) {Object} response
     * @apiSuccessExample 响应结果示例
     * {}
     */
    @PostMapping("/warmUser")
    @ResponseBody
    public R warmUser(@RequestHeader String token, @RequestBody IdForm form) {
        userServiceimpl.warmUser(form.getShopId(), token);
        return R.ok();
    }
}

